//
//  ByViewDetailSegment.m
//  oc_knowledge
//
//  Created by pro on 17/1/18.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByViewDetailSegment.h"

@interface ByViewDetailSegment ()

@property (nonatomic, strong) UIView *selectedView;
@end

@implementation ByViewDetailSegment
{
    NSArray *_segments;
    
    
}
- (instancetype)initWithFrame:(CGRect)frame
                     segments:(NSArray *)segments {
    if (self = [super initWithFrame:frame]) {
        
        _segments = segments;
        [self setupUI];
    }
    return self;
}

- (UIView *)selectedView {
    
    if (!_selectedView) {
        _selectedView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width / _segments.count, 2)];
        _selectedView.backgroundColor = [UIColor orangeColor];
        [self addSubview:_selectedView];
    }
    return _selectedView;
}

- (void)setupUI {
    __block CGFloat x, y, width, height;
    width = self.width / _segments.count;
    height = self.height;
    [_segments enumerateObjectsUsingBlock:^(NSString *text, NSUInteger index, BOOL * _Nonnull stop) {
        x = index * width;
        y = 0;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(x, y, width, height);
        [button setTitle:text forState:UIControlStateNormal];
        [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
        button.titleLabel.font = FONT(16);
        [self addSubview:button];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = index;
        
        if (index == 0) {
            button.selected = YES;
            self.selectedView.x = button.x;
            self.selectedView.bottom = button.height;
        }
    }];
    
}

- (void)buttonClick:(UIButton *)sender {
    
    // 说明点击了当前选中的按钮
    if (sender.selected) {
        return;
    }
    
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull subview, NSUInteger index, BOOL * _Nonnull stop) {
        if ([subview isKindOfClass:[UIButton class]]) {
            ((UIButton *)subview).selected = NO;
        }
    }];
    
    sender.selected = YES;
    if (self.tapAction) {
        self.tapAction(sender.tag, sender.titleLabel.text);
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.selectedView.x = sender.x;
        self.selectedView.bottom = sender.height;
    }];
    
}

@end
